#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import time

import cv2
import numpy as np
import pytesseract
import sys
from matplotlib import pyplot as plt

import logging


def setup_custom_logger(name):
    formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                                  datefmt='%Y-%m-%d %H:%M:%S')
    # handler = logging.FileHandler('log.txt', mode='w')
    # handler.setFormatter(formatter)
    screen_handler = logging.StreamHandler(stream=sys.stdout)
    screen_handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # logger.addHandler(handler)
    logger.addHandler(screen_handler)
    return logger


logger = setup_custom_logger('app')

imageFolder = "mijing2"

card_champion = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/card_champion.png'),
                             cv2.COLOR_BGR2GRAY)
daily_task = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/daily_task.png'),
                          cv2.COLOR_BGR2GRAY)
main_page = cv2.cvtColor(cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing/main_page.png'),
                         cv2.COLOR_BGR2GRAY)


def get_screenshot(i):
    # name = '{:05d}_{}'.format(i, int(time.time()))
    name = '{:05d}'.format(i)
    os.system('adb shell screencap -p /sdcard/book/image/{}.png'.format(name))
    os.system('adb pull /sdcard/book/image/{}.png {}/{}.png'.format(name, imageFolder, name))
    os.system('adb shell rm /sdcard/book/image/{}.png'.format(name))
    return name


def get_screenshot_static():
    res = os.system('adb shell screencap -p /sdcard/book/image/img.png')
    if res == 0:
        res = os.system(
            'adb pull /sdcard/book/image/img.png /home/liusen/IdeaWorkspace/wechat-jump/mijing2/img.png'.format(
                imageFolder))
        if res == 0:
            os.system('adb shell rm /sdcard/book/image/img.png')
            if res == 0:
                return cv2.imread('/home/liusen/IdeaWorkspace/wechat-jump/mijing2/img.png')


def click(location):
    cmd = 'adb shell input swipe %s %s %s %s 100' % (location[0], location[1], location[0], location[1])
    logger.debug('%s' % (cmd))
    os.system(cmd)


def test1():
    name = get_screenshot(19)
    # path = os.path.join(imageFolder, name + '.png')
    # img_rgb = cv2.imread(path)
    # img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    # cv2.imwrite('{}/{}_last.png'.format(imageFolder, name), img_gray)
    # time.sleep(1.5)


def getContentMainPage(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[382:403, 417:467]
    frame_threshed = cv2.inRange(img, 0, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    template = main_page
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()
    # cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing/main_page.png', img)
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.8)
    if len(list(zip(*loc[::-1]))) >= 1:
        logger.debug("main_page match value : {}".format(res[0][0]))
        return True
    else:
        return False


def getContentDailyTask(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[124:156, 575:705]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    # plt.imshow(img), plt.show()
    template = daily_task
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.8)
    if len(list(zip(*loc[::-1]))) >= 1:
        logger.debug("daily_task match value : {}".format(res[0][0]))
        return True
    else:
        return False


def getContentCardChampion(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    img = img[350:386, 86:156]
    frame_threshed = cv2.inRange(img, 87, 255)
    img = cv2.bitwise_or(img, img, mask=frame_threshed)
    template = card_champion
    # plt.imshow(img), plt.show()
    # plt.imshow(template), plt.show()

    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.8)
    # cv2.imwrite('/home/liusen/IdeaWorkspace/wechat-jump/mijing/card_champion.png', img)
    if len(list(zip(*loc[::-1]))) >= 1:
        logger.debug("card_champion match value : {}".format(res[0][0]))
        return True
    else:
        return False


def test2():
    for i in range(100000):
        logger.debug('-----start handle process-----')
        img = get_screenshot_static()
        if img is not None:
            # 如果有日常任务就点关闭
            if getContentDailyTask(img):
                logger.debug('关闭日常任务')
                click([1018, 143])
                continue
            # 如果是主页面 就点击进入对决模式
            if getContentMainPage(img):
                logger.debug('进入对决模式')
                click([637, 271])
                continue
            if getContentCardChampion(img):
                logger.debug('遇到擂主了，认真玩吧')
                time.sleep(300)
                # sys.exit(0)
                continue
            if i % 3 == 0:
                click([560, 650])
            if i % 3 == 1:
                click([1100, 450])
            if i % 3 == 2:
                click([1220, 660])
        time.sleep(0.4)
        logger.debug('------handle process end-------')


if __name__ == '__main__':
    test2()
    # get_screenshot(1)
